using Microsoft.EntityFrameworkCore;
using OrderingSystem.Core.Entities;
using OrderingSystem.Core.Interfaces;
using OrderingSystem.Infrastructure.Data;

namespace OrderingSystem.Infrastructure.Services
{
    public class ChatService : IChatService
    {
        private readonly ApplicationDbContext _context;

        public ChatService(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task<IEnumerable<Chat>> GetChatsAsync()
        {
            return await _context.Chats
                .OrderByDescending(c => c.addtime)
                .ToListAsync();
        }

        public async Task<IEnumerable<Chat>> GetUserChatsAsync(long userId)
        {
            return await _context.Chats
                .Where(c => c.userid == userId)
                .OrderByDescending(c => c.addtime)
                .ToListAsync();
        }

        public async Task<Chat> GetChatAsync(long id)
        {
            return await _context.Chats
                .FirstOrDefaultAsync(c => c.id == id);
        }

        public async Task<Chat> CreateChatAsync(Chat chat)
        {
            chat.addtime = DateTime.Now;
            chat.isreply = 0;

            _context.Chats.Add(chat);
            await _context.SaveChangesAsync();
            return chat;
        }

        public async Task<Chat> ReplyChatAsync(long id, string reply)
        {
            var chat = await _context.Chats.FindAsync(id);
            if (chat == null)
            {
                return null;
            }

            chat.reply = reply;
            chat.isreply = 1;

            await _context.SaveChangesAsync();
            return chat;
        }

        public async Task DeleteChatAsync(long id)
        {
            var chat = await _context.Chats.FindAsync(id);
            if (chat != null)
            {
                _context.Chats.Remove(chat);
                await _context.SaveChangesAsync();
            }
        }
    }
} 